package com.sphd.restaurantsystem.activitys.foods;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.adapters.FoodMenuAdapter;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.info.GreensInfo;
import com.sphd.restaurantsystem.info.LoginInfo;
import com.sphd.restaurantsystem.info.RestaurantInfo;
import com.sphd.restaurantsystem.info.SortInfo;
import com.sphd.restaurantsystem.presenter.FoodMenuPresenterImpl;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.view.FoodMenuView;

import org.litepal.crud.DataSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
* 菜单的界面
* */
public class FoodMenuActivity extends BaseActivity implements FoodMenuView {

    private static final int BLANK_CODE = 0;
    private static final int NO_BLANK_CODE = 1;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.content_food_menu)
    RelativeLayout contentFoodMenu;
    Bundle bundle;
    Intent intent;
    SortInfo sortInfo;
    FoodMenuPresenterImpl foodMenuPresenter;
    @BindView(R.id.add_food)
    ImageView addFood;
    private int curpage = 1;
    FoodMenuAdapter foodMenuAdapter;
    RestaurantInfo restaurantInfo;
    LoginInfo loginInfo;
    int position = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_menu);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(view -> finish());
        mySwf.setOnRefreshListener(() -> {
            curpage=1;
            addData();
        });
        myRecy.addOnItemTouchListener(new OnItemClickListener() {
                                          @Override
                                          public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                                              if (isManagerCanDo(loginInfo,restaurantInfo)){
                                                  position = i;
                                                  bundle.putInt(Constant.TYPE, NO_BLANK_CODE);
                                                  bundle.putSerializable(Constant.GREENSINFO, (Serializable) baseQuickAdapter.getItem(i));
                                                  intent.putExtras(bundle);
                                                  intent.setClass(context, FoodInfomationActivity.class);
                                                  startActivityForResult(intent, 1);
                                              }
                                          }

                                          @Override
                                          public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                                              super.onItemLongClick(adapter, view, position);
                                              Log.e(TAG, isCg_has_storemanager(restaurantInfo) + "==" +
                                                      restaurantInfo.getCg_name() + "-----" + isSuperManager(loginInfo));
                                              if (isCg_has_storemanager(restaurantInfo) && isSuperManager(loginInfo)) {
                                                  toast("店长会去操作，您不用费心了");
                                              } else {
                                              delFood((GreensInfo) adapter.getItem(position), position);
                                              }
                                          }

                                      }

        );
        foodMenuAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curpage++;
                addData();
            }
        });

    }

    private void delFood(GreensInfo greensInfo, int position) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder
                .setTitle("删除提示")
                .setMessage("确定要删除" + greensInfo.getDishes_name() + "吗?")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        confimDel(greensInfo, position);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
    }

    private void confimDel(GreensInfo greensInfo, int position) {
        foodMenuPresenter.delItem(RestaurantUrl.Httptitle + RestaurantUrl.DelFood
                + "dishesid=" + greensInfo.getId());
        this.position = position;
    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        loginInfo = DataSupport.findLast(LoginInfo.class);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        sortInfo = (SortInfo) bundle.getSerializable(Constant.SORTINFO);
        setTitleBar(toolbar, sortInfo.getSort());
        foodMenuPresenter = new FoodMenuPresenterImpl(this);
        if (isCg_has_storemanager(restaurantInfo)&&isSuperManager(loginInfo)){
            addFood.setVisibility(View.GONE);
        }else {
            addFood.setVisibility(View.VISIBLE);
        }

        initAdapter();
        addData();
    }

    private void initAdapter() {
        setRefresh(mySwf);
        setGRecy(myRecy, 3);
        foodMenuAdapter = new FoodMenuAdapter(R.layout.item_foot_ment, new ArrayList<>());
        foodMenuAdapter.openLoadMore(10);
        foodMenuAdapter.openLoadAnimation();
        myRecy.setAdapter(foodMenuAdapter);
    }

    private void addData() {
        foodMenuPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.Showfood + "cgid=" + sortInfo.getCgid() + "&sortid=" + sortInfo.getId()
                + "&curpage=" + curpage + "&pageno=10");

    }

    @Override
    public void recRes(List<GreensInfo> greensInfos) {

        if (curpage == 1) {
            foodMenuAdapter.setNewData(greensInfos);
        } else {
            foodMenuAdapter.addData(greensInfos);
        }
        if (greensInfos.size()!=10){
            foodMenuAdapter.loadComplete();
        }
    }

    @Override
    public void delSucced() {
        toast("删除成功");
        curpage = 1;
        addData();
    }

    @Override
    public void delError() {
        toast("删除失败，请重试。");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("====", resultCode + "");
        if (resultCode == 1) {
            // TODO: 2016/11/17
            curpage = 1;
            addData();
        } else if (resultCode == 2) {

        }
    }


    @OnClick(R.id.add_food)
    public void onClick() {
        bundle.putInt(Constant.TYPE, BLANK_CODE);
        intent.putExtras(bundle);
        intent.setClass(context, FoodInfomationActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
        mySwf.setRefreshing(false);
    }
}
